package vip.george.p0007;

public class P7 {

    public int reverse(int x) {
        // 结果使用long型，避免反转后的数值溢出
        long result = 0;
        while (x != 0) {
            int pop = x % 10; // 取末尾(注意，这个是带符号的)
            x = x / 10;
            result = result * 10 + pop;
            if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
                return 0;
            }
        }
        return (int) result;
    }


    public int reverse2(int x) {
        boolean isNegative = x < 0;
        // 转为正数进行处理
        long result = x;
        result = isNegative ? -result : result;
        StringBuilder sb = new StringBuilder(String.valueOf(result));
        result = Long.parseLong(sb.reverse().toString());
        // 反转后的结果和原始数值的符号一致
        result = isNegative ? -result : result;
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0;
        } else {
            return (int) result;
        }
    }

    public static void main(String[] args) {
        P7 p7 = new P7();
        System.out.println(p7.reverse(-123));
        System.out.println(p7.reverse(123));
        System.out.println(p7.reverse(1534236469));

        System.out.println("=================");

        System.out.println(p7.reverse2(-123));
        System.out.println(p7.reverse2(123));
        System.out.println(p7.reverse2(-2147483648));
        System.out.println(p7.reverse2(1534236469));
    }
}
